/*
 * Copyright (c) 2010, Oracle. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of Oracle nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

package br.com.uff.ihc.ontologico.view;

import br.com.uff.ihc.ontologico.modelo.Conceito;
import br.com.uff.ihc.ontologico.modelo.Ontologia;
import br.com.uff.ihc.ontologico.modelo.Relacionamento;
import br.com.uff.ihc.ontologico.util.FileUtil;
import com.thoughtworks.xstream.XStream;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.picking.PickedState;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;

public class OntoLogico extends javax.swing.JFrame {
    
    VisualizationViewer<Conceito,Relacionamento> vv;
    private DirectedGraph<Conceito, Relacionamento> g;
    private Ontologia ontologia;
    private String textoSelecionado;

    public OntoLogico() {
        initComponents();
        g = new DirectedSparseMultigraph<Conceito, Relacionamento>();        redesenharGrafo();        
        ontologia = new Ontologia();
        
        jButton1.setBorder(BorderFactory.createEmptyBorder());
        jButton1.setContentAreaFilled(false);
        jButton2.setBorder(BorderFactory.createEmptyBorder());
        jButton2.setContentAreaFilled(false);
        jButton4.setBorder(BorderFactory.createEmptyBorder());
        jButton4.setContentAreaFilled(false);
        jButton7.setBorder(BorderFactory.createEmptyBorder());
        jButton7.setContentAreaFilled(false);
        jButton8.setBorder(BorderFactory.createEmptyBorder());
        jButton8.setContentAreaFilled(false);
        jButton3.setBorder(BorderFactory.createEmptyBorder());
        jButton3.setContentAreaFilled(false);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        scrollPane1 = new java.awt.ScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();

        org.jdesktop.layout.GroupLayout jFrame1Layout = new org.jdesktop.layout.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("OntoLogico");

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/uff/ihc/ontologico/view/img/Link-icon.png"))); // NOI18N
        jButton2.setToolTipText("Associar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/uff/ihc/ontologico/view/img/1354037533_netvibes.png"))); // NOI18N
        jButton1.setToolTipText("Novo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Texto"));

        jTextPane1.setBackground(new java.awt.Color(229, 242, 242));
        jScrollPane1.setViewportView(jTextPane1);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1)
        );

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/uff/ihc/ontologico/view/img/1354040146_recycle_bin.png"))); // NOI18N
        jButton3.setToolTipText("Excluir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/uff/ihc/ontologico/view/img/1354039520_Close_Box_Red.png"))); // NOI18N
        jButton4.setToolTipText("Desassociar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Importar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/uff/ihc/ontologico/view/img/Actions-document-edit-icon.png"))); // NOI18N
        jButton7.setToolTipText("Editar");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/uff/ihc/ontologico/view/img/1354040032_gnome-searchtool.png"))); // NOI18N
        jButton8.setToolTipText("Localizar");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jButton6.setText("Exportar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Ontologia"));

        scrollPane1.setBackground(new java.awt.Color(236, 247, 236));

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, scrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(scrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Documentos"));

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 93, Short.MAX_VALUE)
        );

        jMenu3.setText("Arquivo");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Abrir arquivo texto");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Importar");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setText("Exportar");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem3);

        jMenuBar2.add(jMenu3);

        jMenu4.setText("Ajuda");

        jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMenuItem4.setText("Conteúdo da Ajuda");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu4.add(jMenuItem4);

        jMenuBar2.add(jMenu4);

        setJMenuBar(jMenuBar2);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(22, 22, 22)
                        .add(jButton5)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(431, 431, 431)
                        .add(jButton6)
                        .add(25, 25, 25))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(10, 10, 10)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jButton5)
                            .add(jButton6))
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 56, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 52, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(0, 55, Short.MAX_VALUE))))
        );

        jPanel3.getAccessibleContext().setAccessibleName(" System");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        textoSelecionado = jTextPane1.getSelectedText();
        NovoConceito novoConceitoWindow = new NovoConceito(this, true, null, textoSelecionado);
        novoConceitoWindow.setLocationRelativeTo(this);
        novoConceitoWindow.setVisible(true);
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        NovoRelacionamento novoRelacionamentoWindow = new NovoRelacionamento(this, true, ontologia.getConceitos());
        novoRelacionamentoWindow.setLocationRelativeTo(this);
        novoRelacionamentoWindow.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        final PickedState<Conceito> pickedState = vv.getPickedVertexState();
        
        Set<Conceito> conceitos = pickedState.getPicked();
                 
        if(conceitos != null && conceitos.size() > 0) {
            solicitarConfirmacaoExclusaoConceito(conceitos);
        }else{
                JOptionPane.showMessageDialog(this, "Selecione pelo menos um conceito.",
		                      "Excluir Conceito", JOptionPane.WARNING_MESSAGE);
        }

//        RemoverConceito removerConceitoWindow = new RemoverConceito(this, true, ontologia.getConceitos());
//        removerConceitoWindow.setLocationRelativeTo(this);
//        removerConceitoWindow.setVisible(true);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        final PickedState<Relacionamento> pickedState = vv.getPickedEdgeState();
        Set<Relacionamento> relacionamentos = pickedState.getPicked();
        if(relacionamentos != null && relacionamentos.size() > 0) {
            removerRelacionamentos(relacionamentos);
        }else{
                JOptionPane.showMessageDialog(this, "Selecione pelo menos um relacionamento.",
		                      "Excluir Relacionamento", JOptionPane.WARNING_MESSAGE);
        }
        
//        RemoverRelacionamento removerRelacionamentoWindow = new RemoverRelacionamento(this, true, ontologia.getConceitos());
//        removerRelacionamentoWindow.setLocationRelativeTo(this);
//        removerRelacionamentoWindow.setVisible(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        AbrirArquivo abrirArquivoWindow = new AbrirArquivo(this, true);
        abrirArquivoWindow.setLocationRelativeTo(this);
        abrirArquivoWindow.setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        XStream xstream = new XStream();
        ontologia.setTexto(jTextPane1.getText());
        String xml = xstream.toXML(ontologia);
        
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Salvar Ontologia");
        fileChooser.setSelectedFile(new File("Ontologia.xml"));
        fileChooser.addChoosableFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.getName().endsWith(".xml");
            }

            @Override
            public String getDescription() {
                return "Arquivos XML (*.xml)";
            }
        });
        
        int returnVal = fileChooser.showSaveDialog(this);
        if(returnVal == 0){
            File f = fileChooser.getSelectedFile();
            FileUtil.escreverArquivo(f, xml);
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Abrir Ontologia");
        fileChooser.addChoosableFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().endsWith(".xml");
            }

            @Override
            public String getDescription() {
                return "Arquivos XML (*.xml)";
            }
        });
        
        int returnVal = fileChooser.showOpenDialog(this);
        if(returnVal == 0){
            File f = fileChooser.getSelectedFile();
            String xml = FileUtil.lerArquivoTexto(f);
            importarOntologia(xml);
         }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        jButton5ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        jButton6ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        final PickedState<Conceito> pickedState = vv.getPickedVertexState();
        
        Set<Conceito> conceitos = pickedState.getPicked();
                 
        if(conceitos != null && conceitos.size() > 0){
            if(conceitos.size() > 1){
                JOptionPane.showMessageDialog(this, "Selecione somente um conceito.",
				                       "Edição de Conceito", JOptionPane.WARNING_MESSAGE);
            }
            else{
                textoSelecionado = jTextPane1.getSelectedText();
                NovoConceito novoConceitoWindow = new NovoConceito(this, true, ((Conceito)conceitos.toArray()[0]), null);
                novoConceitoWindow.setLocationRelativeTo(this);
                novoConceitoWindow.setVisible(true);
            }
        }else{
                JOptionPane.showMessageDialog(this, "Selecione pelo menos um conceito.",
		                      "Edição de Conceito", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        Localizar localizarWindow = new Localizar(this, true);
        localizarWindow.setLocationRelativeTo(this);
        localizarWindow.setVisible(true);
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        Ajuda ajudaWindow = new Ajuda(this, true);
        ajudaWindow.setLocationRelativeTo(this);
        ajudaWindow.setVisible(true);
    }//GEN-LAST:event_jMenuItem4ActionPerformed
    
    public static void main(String args[]) {
        try {
            javax.swing.UIManager.LookAndFeelInfo[] installedLookAndFeels=javax.swing.UIManager.getInstalledLookAndFeels();
            for (int idx=0; idx<installedLookAndFeels.length; idx++){
                if ("Windows".equals(installedLookAndFeels[idx].getName())) {
                    javax.swing.UIManager.setLookAndFeel(installedLookAndFeels[idx].getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(OntoLogico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }       
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OntoLogico().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    private java.awt.ScrollPane scrollPane1;
    // End of variables declaration//GEN-END:variables

    void addConceito(String termo, String descricao) {
        Conceito conceito = new Conceito(termo, descricao, textoSelecionado);
        ontologia.addConceito(conceito);
        g.addVertex(conceito);
        
        redesenharGrafo();
        

//        g2.addEdge("Edge-B", 2,3, EdgeType.DIRECTED);
//        g2.addEdge("Edge-C", 3, 2, EdgeType.DIRECTED);

    }


    private void redesenharGrafo() {
        Layout<Conceito,Relacionamento> layout = new CircleLayout(g);
        layout.setSize(new Dimension(300,300));
        vv = new VisualizationViewer<Conceito,Relacionamento>(layout);
        vv.setBackground(new java.awt.Color(236, 247, 236));
        vv.setPreferredSize(new Dimension(350,350));
        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
        vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
        vv.getRenderContext().setLabelOffset(20);
        // Create a graph mouse and add it to the visualization component
        DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
        gm.setMode(ModalGraphMouse.Mode.PICKING);
        vv.setGraphMouse(gm);
        vv.addKeyListener(gm.getModeKeyListener());
//        vv.setVertexToolTipTransformer(new Transformer<Conceito, String>() {
//
//            public String transform(Conceito i) {
//                return i.getDescricao();
//            }
//        });
        // Set up a new stroke Transformer for the edges
        //float dash[] = {10.0f};
        //final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
        //BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
//        Transformer<Relacionamento, Stroke> edgeStrokeTransformer = new Transformer<Relacionamento, Stroke>() {
//            public Stroke transform(Relacionamento s) {
//                return edgeStroke;
//        }
//        };
        //vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
        
        final PickedState<Conceito> pickedState = vv.getPickedVertexState();

        // Attach the listener that will print when the vertices selection changes.
        pickedState.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                Object subject = e.getItem();
                if (subject instanceof Conceito) {
                    Conceito conceito = (Conceito) subject;
                    if (pickedState.isPicked(conceito) && conceito.getTextoSelecionado() != null) {
                        jTextPane1.getHighlighter().removeAllHighlights();
                        String textoSemEscapes = jTextPane1.getText().replaceAll("\n", "");
                        int selectionStart = textoSemEscapes.indexOf(conceito.getTextoSelecionado());
                        
                        if(selectionStart >= 0){
                            DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
                            try {
                                jTextPane1.getHighlighter().addHighlight(selectionStart, selectionStart + conceito.getTextoSelecionado().length(),
                                        highlightPainter);
                            } catch (BadLocationException ex) {
                                Logger.getLogger(OntoLogico.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    } else {
                        jTextPane1.getHighlighter().removeAllHighlights();
//                        System.out.println("Vertex " + conceito
//                            + " no longer selected");
                    }
                }
            }
        });

        //vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
        
        scrollPane1.add(vv);
        scrollPane1.repaint();
    }

    void addRelacionamento(Conceito conceitoDe, Conceito conceitoPara, String tipoRelacionamento) {
        Relacionamento relacionamento = conceitoDe.addRelacionamento(conceitoPara, tipoRelacionamento);
        
        g.addEdge(relacionamento, conceitoDe, conceitoPara);
        redesenharGrafo();
    }

    void remover(Set<Conceito> conceitos) {
        jTextPane1.getHighlighter().removeAllHighlights();
        
        for (Conceito conceito : conceitos) {
            ontologia.removerConceito(conceito.getId());
            g.removeVertex(conceito);
        }
        
        redesenharGrafo();
    }

    void solicitarConfirmacaoExclusaoConceito(Set<Conceito> conceitos) {
        RemoverConceitoConfirmar removerConceitoConfirmarWindow = new RemoverConceitoConfirmar(this, true, conceitos);
        removerConceitoConfirmarWindow.setLocationRelativeTo(this);
        removerConceitoConfirmarWindow.setVisible(true);
    }

    void removerRelacionamentos(Set<Relacionamento> relacionamentos) {
        jTextPane1.getHighlighter().removeAllHighlights();
        
        for (Relacionamento relacionamento : relacionamentos) {
            relacionamento.getConceitoRelacionador().removerRelacionamento(relacionamento.getConceito().getId());
            g.removeEdge(relacionamento);
        }
        
        redesenharGrafo();
    }
    
    void carregarTexto(String texto) {
        jTextPane1.setText(texto);
    }

    private void importarOntologia(String xml) {
        XStream xstream = new XStream();
        ontologia = (Ontologia) xstream.fromXML(xml);
        g = new DirectedSparseMultigraph<Conceito, Relacionamento>();
        for (Conceito conceito : ontologia.getConceitos()) {
            g.addVertex(conceito);
        }
        for (Conceito conceito : ontologia.getConceitos()) {
            for (Relacionamento relacionamento : conceito.getRelacionamentos()) {
                g.addEdge(relacionamento, conceito, relacionamento.getConceito());
            }
        }
        
        jTextPane1.setText(ontologia.getTexto());
        
        redesenharGrafo();
    }

    void editarConceito(Conceito conceitoExistente) {
        conceitoExistente.setTextoSelecionado(textoSelecionado);
        redesenharGrafo();
    }

    void localizar(String localizar) {
        final PickedState<Conceito> pickedState = vv.getPickedVertexState();
        pickedState.clear();
        
        for (Conceito conceito : ontologia.getConceitos()) {
            if(conceito.getTermo().indexOf(localizar) >=0 || conceito.getDescricao().indexOf(localizar) >= 0 || (conceito.getTextoSelecionado() != null && conceito.getTextoSelecionado().indexOf(localizar) >= 0)){
                pickedState.pick(conceito, true);
            }
        }
    }
    
}
